import { change_role_status, create_role, delete_role, role_list, update_role } from '@/services/admin/role/role';
import { useEffect, useRef, useState } from 'react';
import styles from './role.less';
import { PageContainer } from '@ant-design/pro-layout'
import ProTable from '@ant-design/pro-table'
import type { ProColumnType, ActionType } from '@ant-design/pro-table';
import { Button, Card, Modal, message, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import ProForm, { ProFormText, ProFormSwitch, ProFormTextArea } from '@ant-design/pro-form'
import { Link } from 'umi'
import { Popconfirm } from 'antd';

export default function Page() {
  const actionRef = useRef<ActionType>();
  // 管理员修改modal
  const [EditModalVisible, setEditModalVisible] = useState(false)
  // 管理员创建modal
  const [AddModalVisible, setAddModalVisible] = useState(false)
  // 当前选中角色
  const [onRole, setonRole] = useState<Role.Update>()

  // 角色启用
  const roleEnable = async (d: Role.DataItem) => {
    const res = await change_role_status({ role_id: d.id, role_status: true })
    if (res.code === 200) {
      message.success(res.message)
      actionRef.current?.reload()
      return
    }
    message.info(res.message)
    window.console.log(d)
  }
  /**
   * 删除角色
   * @param d 
   */
  const roleDelete = async (d: Role.DataItem) => {
    const res = await delete_role({ role_id: d.id })
    if (res.code === 200) {
      message.success(`角色 ${d.role_name} 删除成功`)
      actionRef.current?.reload()
    }
    window.console.log(d, res)
  }

  /**
   * 角色禁用
   * @param d 
   */
  const roleDisabled = async (d: Role.DataItem) => {
    const res = await change_role_status({ role_id: d.id, role_status: false })
    if (res.code === 200) {
      message.success(res.message)
      actionRef.current?.reload()
      return
    }
    message.info(res.message)
    window.console.log(d)
  }
  /**
   * 管理员修改窗口
   */
  const editRole = async (d: Role.Update) => {
    window.console.log(d)
    setonRole(d)
    setEditModalVisible(!EditModalVisible)
  }
  const updateRole = async (v: Role.Update) => {
    const res = await update_role({
      role_id: onRole?.id,
      role_name: v.role_name,
      role_status: v.role_status,
      role_desc: v.role_desc
    })
    if (res.code === 200) {
      message.success(res.message)
      setEditModalVisible(!EditModalVisible)
      actionRef.current?.reload()
      return
    }
    message.info(res.message)
  }
  /**
   * 管理员添加窗口
   */
  const addModal = async () => {
    setAddModalVisible(!AddModalVisible)
  }
  /**
   * 创建角色
   * @param values API.AdminForm
   */
  const createRole = async (values: Role.CreateRole) => {
    window.console.log(values)
    await create_role(values)
    message.success("创建成功")
    actionRef.current?.reload()
    setAddModalVisible(false)
  }
  // 导出excel
  const toexcle = () => {
  }
  // 表格列配置
  const Columns: ProColumnType<Role.DataItem>[] = [
    { title: "角色名称", dataIndex: "role_name", valueType: "text" },
    { title: "备注", dataIndex: "role_desc", valueType: "text", hideInSearch: true },
    { title: "创建时间", dataIndex: "create_time", valueType: "dateTime", hideInSearch: true },
    { title: "更新时间", dataIndex: "update_time", valueType: "dateTime", hideInSearch: true },
    {
      title: "状态",
      dataIndex: "role_status",
      valueEnum: {
        true: { text: '已启用', status: 'Success' },
        false: { text: '未启用', status: 'Error' },
      },
      order: 1
    },
    {
      title: "操作", fixed: 'right', width: 280, valueType: "text", render: (r, d) => [
        <Button size="small" className={styles.tbbutton} onClick={async () => {
          await roleEnable(d)
        }} key="enabel" hidden={d.role_status} type="primary">启用</Button>,
        <Button size="small" className={styles.tbbutton} onClick={async () => {
          await roleDisabled(d)
        }} key="disabel" hidden={!d.role_status} danger>禁用</Button>,
        <Button size="small" className={styles.tbbutton} onClick={async () => {
          await editRole(d)
        }} key="setrules">编辑</Button>,
        <Link key="gotoscopes" to={`/admin/role/configrule?role=${d.id}&role_name=${d.role_name}`}>
          <Button size="small" className={styles.tbbutton} key="setscopes" type="ghost">权限分配</Button>
        </Link>,
        <Popconfirm
          key={d.id}
          placement="topLeft"
          title={`确定删除 ${d.role_name} 角色吗`}
          onConfirm={async () => {
            await roleDelete(d)
          }}
          okText="Yes"
          cancelText="No"
        >
          <Button size="small" className={styles.tbbutton} key="delete" type="primary" danger>删除</Button></Popconfirm>,
      ]
    },
  ]
  useEffect(() => {
    return () => {
    }
  }, [])
  return (
    <PageContainer>
      <Card>
        <ProTable<Role.DataItem>
          scroll={{ x: 1400 }}
          debounceTime={30}
          actionRef={actionRef}
          size="small"
          columns={Columns}
          pagination={{ pageSize: 10 }}
          request={async (params) => {
            return await role_list(params)
          }}
          locale={{emptyText: "还没有创建角色哟，点击右上方创建按钮添加角色"}}
          // 搜索配置
          search={{
            defaultCollapsed: true,
            labelWidth: 'auto',
            optionRender: ({ searchText, resetText }, { form }) => {
              return [
                <Button
                  key="searchText"
                  type="primary"
                  onClick={() => {
                    form?.submit();
                  }}
                >
                  {searchText}
                </Button>,
                <Button
                  key="resetText"
                  onClick={() => {
                    form?.resetFields();
                  }}
                >
                  {resetText}
                </Button>,
                // <Button key="out">导出</Button>,
              ];
            },
          }}
          tableAlertOptionRender={() => {
            return (
              <Space size={16}>
                <a>批量删除</a>
                <a onClick={toexcle}>导出数据</a>
              </Space>
            );
          }}
          toolBarRender={() => [
            <Button key="add_role" type="primary" onClick={addModal}>
              <PlusOutlined />
            添加角色
          </Button>,
          ]}
          // 多选框
          // rowSelection={{ selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT] }}
        >
        </ProTable>
      </Card>
      <Modal
        title="创建角色"
        visible={AddModalVisible}
        onCancel={() => { setAddModalVisible(!AddModalVisible) }}
        footer={false}
        destroyOnClose={true}
      >
        <ProForm
          onFinish={createRole}
          submitter={{ searchConfig: { submitText: "创建" } }}
        >
          <ProForm.Item label="角色名称">
            <ProFormText name="role_name"
              rules={[
                { required: true, message: "请输入角色名称" },
                { min: 2, message: "角色名称至少2个字符" }
              ]}
            ></ProFormText>
          </ProForm.Item>
          <ProForm.Item label="备注">
            <ProFormTextArea name="role_desc"></ProFormTextArea>
          </ProForm.Item>
          <ProForm.Item>
            <ProFormSwitch
              label="启用状态"
              name="role_status"
              initialValue={true}
              checkedChildren="开启"
              unCheckedChildren='关闭'
            ></ProFormSwitch>
          </ProForm.Item>
        </ProForm>
      </Modal>
      <Modal
        title="编辑角色"
        visible={EditModalVisible}
        onCancel={() => { setEditModalVisible(!EditModalVisible) }}
        footer={false}
        destroyOnClose={true}
      >
        <ProForm
          onFinish={updateRole}
          submitter={{ searchConfig: { submitText: "更新" }, resetButtonProps: { hidden: true } }}
        >
          <ProForm.Item label="角色名称">
            <ProFormText name="role_name"
              initialValue={onRole?.role_name}
              rules={[
                { required: true, message: "请输入角色名称" },
                { min: 2, message: "角色名称至少2个字符" }
              ]}
            ></ProFormText>
          </ProForm.Item>
          <ProForm.Item label="备注">
            <ProFormTextArea name="role_desc" initialValue={onRole?.role_desc}></ProFormTextArea>
          </ProForm.Item>
          <ProForm.Item>
            <ProFormSwitch
              label="启用状态"
              name="role_status"
              initialValue={onRole?.role_status}
              checkedChildren="开启"
              unCheckedChildren='关闭'
            ></ProFormSwitch>
          </ProForm.Item>
        </ProForm>
      </Modal>
    </PageContainer>
  );
}
